package sheepmixView.client;

import java.util.LinkedList;

import sheepmixView.client.model.Musique;




import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ListBox;

public class GenreSelection implements EntryPoint {

	// Commande RPC
	private PlayingCommandAsync command = PlayingCommand.Util.getInstance();

	// Liste obtenue par le serveur
	LinkedList<LinkedList<Genre>>  listAffichage;
	LinkedList<String>			   listGenre     = new LinkedList<String>();

	// Variables de mise en forme du contenu
	private static final int INTERVAL_INTER_BLOC = 20;
	//private static final int HAUTEUR_BARRE_HORIZONTALE = 100;
	private static int		 largeurEcran = 1366;
	private static int       hauteurEcran = 768;
	private static int       largeurBloc = 80;
	private static int       hauteurBloc = 80;
	private static int       marge;
	private static int       nbMaxBlocsParLignes;
	private static int       nbMaxBlocsParColonnes;
	private static int       nbMaxBlocs;
	private static int       pageEnCours = 0;
	private static int       nbPages = 1;
	private static int       tailleIcones = 64;
	private static int       tailleSheepPass = 166;
	private static boolean   selectall = false;
	private RootPanel        rootPanel;
	private LinkedList<AbsolutePanel>    genrePanel;
	private AbsolutePanel    menuGenrePanel, menuPlayPanel, playPanel;
	//private static int       hauteurPanelMenu  = tailleIcones;
	private static int       hauteurPanelGenre = hauteurEcran - tailleIcones;
	private static boolean   MorceauEnTransition = false;

	String titreTemp = "--";
	String auteurTemp = "--";
	String albumTemp = "--";
	private ListBox          playlistAffichable = new ListBox();
	private ListBox			 playlistTemp = new ListBox();


	// Boutons menu genre
	Image btnNext;
	Image btnPred;
	Image btnLoad;
	Image btnSelect;
	Image btnRefresh;
	Image btnExit;

	// Boutons menu play
	Image btnPlay;
	Image btnStop;
	Image btnPass, btnPass2;
	Image btnHome;
	Label lblTitreDeLa;
	Label lblAuteur;
	Label lblAlbum;

	//	Image btnPlus;
	//	Image btnMinus;



	Image fondEcran;



	private void toutSelectionner(boolean b) {
		for (int i = 0; i < listAffichage.size(); i++) {
			for (int j = 0; j < listAffichage.get(i).size(); j++) {
				listAffichage.get(i).get(j).setSelected(b);
			}
		}
	}

	private void setPochette(LinkedList<Genre> genres) {
		System.out.println("Set Pochette !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		for(int i  = 0; i < genres.size(); i++) {

			final Genre g = genres.get(i);

			command.getImage(genres.get(i).getName(), new AsyncCallback<String>() {

				@Override
				public void onFailure(Throwable caught) {

					System.out.println("Got failure to obtain genre image...");	
				}

				@Override
				public void onSuccess(String result) {
					g.setUrl(result);
				}

			});
		}
		System.out.println("Fin Set Pochette !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
	}

	public static native void closeBrowser()
	/*-{
        $wnd.close();
    }-*/; 

	private void dessinerMenuGenre() {

		// Creation du menu
		menuGenrePanel = new AbsolutePanel();
		menuGenrePanel.setSize(largeurEcran+"px", tailleIcones +"px");
		rootPanel.add(menuGenrePanel, 0, hauteurEcran - tailleIcones);

		// Parametrage des boutons de menu
		//----------------------------------Precedent
		btnPred = new Image("pred.png");
		btnPred.setSize(tailleIcones + "px", tailleIcones + "px");
		btnPred.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				afficherGenre(Math.abs((pageEnCours - 1) % nbPages));
				System.out.println("page en cours   : "+pageEnCours);
				System.out.println("nombre de pages : "+nbPages);
			}
		});
		menuGenrePanel.add(btnPred,0 + marge,0);
		btnPred.setPixelSize(tailleIcones, tailleIcones);

		//----------------------------------Suivant
		btnNext = new Image("next.png");
		btnNext.setSize(tailleIcones + "px", tailleIcones + "px");
		btnNext.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				afficherGenre((pageEnCours + 1) % nbPages);
				System.out.println("page en cours   : "+pageEnCours);
				System.out.println("nombre de pages : "+nbPages);
			}
		});
		menuGenrePanel.add(btnNext,largeurEcran - tailleIcones - marge, 0);

		//----------------------------------Tout selectionner / deselectioner

		btnSelect = new Image("unselect.png");
		btnSelect.setSize(tailleIcones + "px", tailleIcones + "px");
		btnSelect.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if(!selectall) {
					selectall = true;
					btnSelect.setUrl("selectall.png");
				}
				else {
					selectall = false;
					btnSelect.setUrl("unselect.png");
				}
				toutSelectionner(selectall);
			}
		});
		menuGenrePanel.add(btnSelect, largeurEcran/2 - tailleIcones, 0);

		//----------------------------------Load
		btnLoad = new Image("load.png");
		btnLoad.setSize(tailleIcones + "px", tailleIcones + "px");
		btnLoad.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				LinkedList<String> selectedGenre = new LinkedList<String>();
				for (int i = 0; i < listAffichage.size(); i++) {
					for (int j = 0; j < listAffichage.get(i).size(); j++) {
						if(listAffichage.get(i).get(j).isSelected()) {
							selectedGenre.add(listAffichage.get(i).get(j).getName());
							listAffichage.get(i).get(j).setSelected(false);
						}
					}
				}
				selectall = false;
				if(!selectedGenre.isEmpty()) {
					command.loadGenres(selectedGenre, new AsyncCallback<Void>() {

						@Override
						public void onFailure(Throwable caught) {
							System.out.println("Load failed !");

						}

						@Override
						public void onSuccess(Void result) {
							System.out.println("Load ok !");
						}
					});
				}

				rootPanel.remove(genrePanel.get(pageEnCours));
				rootPanel.remove(menuGenrePanel);
				dessinerMenuPlay();
				dessinerPlayPanel();
			}
		});
		menuGenrePanel.add(btnLoad,largeurEcran/2,0);

		//----------------------------------Exit
		btnExit = new Image("exit.png");
		btnExit.setSize(tailleIcones + "px", tailleIcones + "px");
		btnExit.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				command.stop(new AsyncCallback<Void>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(Void result) {
						// TODO Auto-generated method stub

					}
				});
				closeBrowser();
			}
		});
		menuGenrePanel.add(btnExit, largeurEcran/2 + largeurEcran/4, 0);

		//----------------------------------Refresh
		btnRefresh = new Image("refresh.png");
		btnRefresh.setSize(tailleIcones + "px", tailleIcones + "px");
		btnRefresh.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				Location.reload();
			}
		});
		menuGenrePanel.add(btnRefresh, largeurEcran/2 - largeurEcran/4 - tailleIcones, 0);


	}

	private void dessinerMenuPlay() {
		// Creation du menu
		menuPlayPanel = new AbsolutePanel();
		menuPlayPanel.setSize(largeurEcran+"px", tailleIcones +"px");
		rootPanel.add(menuPlayPanel, 0, hauteurEcran - tailleIcones);

		// Parametrage des boutons de menu

		//----------------------------------stop
		btnStop = new Image("stop.png");
		btnStop.setSize(tailleIcones + "px", tailleIcones + "px");
		btnStop.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				command.stop(new AsyncCallback<Void>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(Void result) {
						// TODO Auto-generated method stub

					}
				});
			}
		});
		menuPlayPanel.add(btnStop, largeurEcran/2 - tailleIcones/2, 0);

		//----------------------------------Play
		btnPlay = new Image("play.png");
		btnPlay.setSize(tailleIcones + "px", tailleIcones + "px");
		btnPlay.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				command.play(new AsyncCallback<Void>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(Void result) {
						// TODO Auto-generated method stub

					}
				});
			}
		});
		menuPlayPanel.add(btnPlay,largeurEcran/2 + tailleIcones,0);

		//----------------------------------Home
		btnHome = new Image("home.png");
		btnHome.setSize(tailleIcones + "px", tailleIcones + "px");
		btnHome.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				rootPanel.remove(menuPlayPanel);
				rootPanel.remove(playPanel);
				dessinerMenuGenre();
				pageEnCours = 0;
				rootPanel.add(genrePanel.get(pageEnCours));
			}
		});
		menuPlayPanel.add(btnHome,largeurEcran/2 - 2*tailleIcones,0);
	}

	private LinkedList<LinkedList<Genre>> obtenirGenre(LinkedList<String> listeGenre) {
		System.out.println("dessinerGenre()");
		LinkedList<LinkedList<Genre>> ls = new LinkedList<LinkedList<Genre>>();
		ls.add(new LinkedList<Genre>());
		int i = 0;
		nbPages = 1;

		for(String genre : listeGenre) {
			if (!listeGenre.isEmpty()) {
				if (ls.get(i).size() > nbMaxBlocs) {
					i++;
					nbPages++;
					setPochette(ls.get(i));
					ls.add(new LinkedList<Genre>());
				}

				ls.get(i).add(new Genre(genre,"noteMusique.png"));
			}
		}
		setPochette(ls.get(i));
		return ls;
	}

	private void creerPanel(LinkedList<String> lg) {
		int currentX = marge;
		int currentY = marge;
		listAffichage = obtenirGenre(lg);
		genrePanel = new LinkedList<AbsolutePanel>();

		// Creation premier panel
		AbsolutePanel p = new AbsolutePanel();
		p.setPixelSize(largeurEcran, hauteurPanelGenre);
		genrePanel.add(p);

		//int page = 0;

		// Remplissage des panels et extension si besoin.
		int j = 1;
		for (int page = 0; page < listAffichage.size(); page++) {

			for (int item = 0; item < listAffichage.get(page).size(); item++) {
				if (j > nbMaxBlocsParLignes)
				{
					j = 1;
					currentX = marge;
					currentY = currentY + hauteurBloc + INTERVAL_INTER_BLOC;
				}
				final Genre tmp = listAffichage.get(page).get(item);
				tmp.addClickHandler(new ClickHandler() {
					public void onClick(ClickEvent event) {
						System.out.println(tmp.getName());
						if(!tmp.isSelected()) {
							tmp.setSelected(true);
						}		
						else{
							tmp.setSelected(false);
						}
					}
				});
				genrePanel.get(page).add(listAffichage.get(page).get(item),currentX, currentY);
				Label label = new Label(listAffichage.get(page).get(item).getName());
				if (label.getText().length() > 12) {
					String s = label.getText();
					s = s.substring(0, 11);
					s += "...";
					label.setText(s);
				}
				label.setStyleName("gwt-Label");
				genrePanel.get(page).add(label,currentX,currentY+hauteurBloc);
				currentX = currentX + largeurBloc + INTERVAL_INTER_BLOC;
				j++;
			}
			j=1;
			currentX = marge;
			currentY = marge;

			p = new AbsolutePanel();
			p.setPixelSize(largeurEcran, hauteurPanelGenre);
			genrePanel.add(p);
		}
	}

	private void afficherGenre(int page) {
		rootPanel.remove(genrePanel.get(pageEnCours));
		rootPanel.add(genrePanel.get(page),0,0);
		pageEnCours = page;
	}


	public void dessinerPlayPanel() {

		playPanel = new AbsolutePanel();
		playPanel.setSize(largeurEcran+"px", hauteurEcran - tailleIcones +"px");
		rootPanel.add(playPanel, 0, 0);

		//----------------------------------Pass
		btnPass = new Image("sheepPass.png");
		btnPass.setSize(tailleSheepPass + "px", tailleSheepPass + "px");
		btnPass.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if (! MorceauEnTransition) {
					btnPass.setUrl("sheepPassDuringTransition.png");
					MorceauEnTransition = true;
					command.pass(new AsyncCallback<Boolean>() {

						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onSuccess(Boolean result) {
							btnPass.setUrl("sheepPass.png");
							MorceauEnTransition = false;
						}
					});
				}
			}
		});
		playPanel.add(btnPass,largeurEcran - (tailleSheepPass + tailleIcones/2) ,tailleIcones/2);


		Label lblT   = new Label("Titre   : ");
		Label lblAut = new Label("Artiste : ");
		Label lblAlb = new Label("Album   : ");
		//final Label lblTime= new Label("--");


		lblT.setStyleName("gwt-Titre");
		lblAut.setStyleName("gwt-Titre");
		lblAlb.setStyleName("gwt-Titre");
		//lblTime.setStyleName("gwt-Titre");


		Image transPlayed = new Image("test.png");
		transPlayed.setPixelSize(750, 300);
		playPanel.add(transPlayed,tailleSheepPass-40,2*tailleSheepPass-40);

		playPanel.add(lblT,tailleSheepPass,2*tailleSheepPass);
		playPanel.add(lblAut,tailleSheepPass,2*tailleSheepPass+tailleIcones);
		playPanel.add(lblAlb,tailleSheepPass,2*tailleSheepPass+2*tailleIcones);
		//playPanel.add(lblTime,tailleSheepPass,2*tailleSheepPass+3*tailleIcones);

		lblTitreDeLa = new Label(titreTemp);
		lblTitreDeLa.setStyleName("gwt-Titre");
		playPanel.add(lblTitreDeLa, tailleSheepPass+lblT.getOffsetWidth() + 20, 2*tailleSheepPass);
		//lblTitreDeLa.setSize("633px", "94px");

		lblAuteur = new Label(auteurTemp);
		lblAuteur.setStyleName("gwt-Titre");
		playPanel.add(lblAuteur, tailleSheepPass+lblAut.getOffsetWidth() + 20, 2*tailleSheepPass+tailleIcones);

		lblAlbum = new Label(albumTemp);
		lblAlbum.setStyleName("gwt-Titre");
		playPanel.add(lblAlbum, tailleSheepPass+lblAlb.getOffsetWidth() + 20, 2*tailleSheepPass+2*tailleIcones);

		playlistAffichable = playlistTemp;
		playlistAffichable.setStyleName("gwt-playlist");
		playlistAffichable.setVisibleItemCount(14);
		playlistAffichable.setSize("600px", "300px");
		playPanel.add(playlistAffichable,largeurEcran - (3*tailleSheepPass), 2*tailleSheepPass-35);




		Timer timer = new Timer() {
			@Override
			public void run() {

				// Musique courante
				command.getCurrentMusique(new AsyncCallback<Musique>() {

					@Override
					public void onFailure(Throwable caught) {

					}

					@Override
					public void onSuccess(Musique result) {
						if (result != null) {

							String tmp = result.getTitre();
							if(tmp.length() > 25) {
								tmp = tmp.substring(0, 24);
								tmp += "...";
							}
							lblTitreDeLa.setText(tmp);
							System.out.println(tmp);
							titreTemp = tmp;

							tmp = result.getAuteur();
							if(tmp.length() > 25) {
								tmp = tmp.substring(0, 24);
								tmp += "...";
							}
							lblAuteur.setText(tmp);
							System.out.println(tmp);
							auteurTemp = tmp;

							tmp = result.getAlbum();
							if(tmp.length() > 25) {
								tmp = tmp.substring(0, 24);
								tmp += "...";
							}
							lblAlbum.setText(tmp);
							System.out.println(tmp);
							albumTemp = tmp;
							//currentTime = 0;
						}
					}
				});

				// Playlist courante
				command.getCurrentPlaylist(new AsyncCallback<LinkedList<Musique>>() {

					@Override
					public void onFailure(Throwable caught) {

					}

					@Override
					public void onSuccess(LinkedList<Musique> result) {
						if(result != null) {
							playlistAffichable.clear();
							for (int i = 0 ; i < result.size(); i++) {
								String tmp = result.get(i).getAuteur()+" - "+result.get(i).getTitre();
								if(tmp.length() > 61) {
									tmp = tmp.substring(0, 61) + "...";
								}
								playlistAffichable.addItem(tmp);
							}
							playlistTemp = playlistAffichable;
						}
					}
				});
			}
		};	
		timer.scheduleRepeating(2000);

	}

	public void onModuleLoad() {
		System.out.println("onModuleLoad()");

		rootPanel = RootPanel.get();
		rootPanel.setSize("1366px", "768px");

		fondEcran = new Image("fondEcran.png");
		rootPanel.add(fondEcran, 0, 0);
		fondEcran.setSize("1366px", "768px");

		// On demande la liste des genres au serveur.
		command.getGenre(new AsyncCallback<LinkedList<String>>() {

			@Override
			public void onFailure(Throwable caught) {
				System.out.println("Get Genre failed !");
			}

			@Override
			public void onSuccess(LinkedList<String> result) {
				System.out.println("Youhou !");
				System.out.println(result);
				listGenre = result;
				creerPanel(listGenre);
				afficherGenre(pageEnCours);
			}

		});

		// On met toutes les musiques dans la liste d'affichage en fonction de sa page ...


		// Initialisation des parametres d'affichage
		nbMaxBlocsParLignes   = (int) ((double) largeurEcran / (((double) INTERVAL_INTER_BLOC + largeurBloc)));
		nbMaxBlocsParColonnes = (int) ((double) (hauteurEcran) / (((double) INTERVAL_INTER_BLOC + hauteurBloc))) - 1;
		marge      = (int) ((largeurEcran - (nbMaxBlocsParLignes * (largeurBloc + INTERVAL_INTER_BLOC) - INTERVAL_INTER_BLOC)) / 2);
		//marge        = (int) ((hauteurEcran - (nbMaxBlocsParColonnes * (hauteurBloc + INTERVAL_INTER_BLOC) - INTERVAL_INTER_BLOC)) / 2);
		nbMaxBlocs            = nbMaxBlocsParLignes * nbMaxBlocsParColonnes - 1;


		// On Dessine la partie genre
		//listAffichage = dessinerGenre(listGenre);
		dessinerMenuGenre();

	}
}
